import axios from 'axios'
import { successResponse, errorResponse } from './utils'
import useUserInfoStore from '@/store/modules/userInfo'

export const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const userInfo = useUserInfoStore().userInfo
    
    // if (userInfo.token) {
    //   config.headers.token = userInfo.token
    // }
    const token = 'eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSCjAK0A0Ndg1S0lFKrShQsjI0NzYyMTMxtDDUUSotTi3yTAGKQZh-ibmpQB2JKbmZeUq1AK141v9BAAAA.Ng88l_XNfiGKvyeUkUsCCjJs5K-LrJHZT4mK6aRAlJZM8isBi73hc2x4eYDL0JPAvuq-4evIWObNaKzw4IC6-A'
    config.headers.token = token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = successResponse(response)    
    if (res){
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    errorResponse(error)
    return Promise.reject(error)
  }
)

/**
 * get方法，对应查询
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} headers [headers配置]
 */
export function get (url: string, params = {}, headers = {}, timeout = 5000) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'get',
      params,
      headers,
      timeout
    })
      .then(res => {
        
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data || err)
      })
  })
}

/**
 * post方法，对应新增
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} headers [headers配置]
 */
export function post (
  url : string,
  data : any,
  // headers = {
  //   'Content-Type': 'application/json;charset=UTF-8'
  // },
  headers = {},
  timeout = 5000
) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      data,
      method: 'post',
      headers,
      timeout
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data || err)
      })
  })
}

/**
 * delete方法，对应删除
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function del (url: string, params = {}) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'delete',
      data: params
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data || err)
      })
  })
}

/**
 * put方法，对应修改
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put (url: string, params : any) {
  return new Promise((resolve, reject) => {
    instance
      .put(url, params)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data || err)
      })
  })
}


